home *** CD-ROM | disk | FTP | other *** search
/ InterCD 2001 November / november_2001.iso / Browsers / Netscape 6.1 / browser.xpi / bin / components / nsSidebar.js < prev    next >
Encoding:
Text File  |  2001-06-21  |  15.6 KB  |  409 lines

  1. /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  2.  * The contents of this file are subject to the Mozilla Public
  3.  * License Version 1.1 (the "License"); you may not use this file
  4.  * except in compliance with the License. You may obtain a copy of
  5.  * the License at http://www.mozilla.org/MPL/
  6.  * 
  7.  * Software distributed under the License is distributed on an "AS
  8.  * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
  9.  * implied. See the License for the specific language governing
  10.  * rights and limitations under the License.
  11.  * 
  12.  * The Original Code is mozilla.org code.
  13.  * 
  14.  * The Initial Developer of the Original Code is Netscape
  15.  * Communications Corporation.  Portions created by Netscape are
  16.  * Copyright (C) 1999 Netscape Communications Corporation.  All
  17.  * Rights Reserved.
  18.  * 
  19.  * Contributor(s): Stephen Lamm            <slamm@netscape.com>
  20.  *                 Robert John Churchill   <rjc@netscape.com>
  21.  */
  22.  
  23. /*
  24.  * No magic constructor behaviour, as is de rigeur for XPCOM.
  25.  * If you must perform some initialization, and it could possibly fail (even
  26.  * due to an out-of-memory condition), you should use an Init method, which
  27.  * can convey failure appropriately (thrown exception in JS,
  28.  * NS_FAILED(nsresult) return in C++).
  29.  *
  30.  * In JS, you can actually cheat, because a thrown exception will cause the
  31.  * CreateInstance call to fail in turn, but not all languages are so lucky.
  32.  * (Though ANSI C++ provides exceptions, they are verboten in Mozilla code
  33.  * for portability reasons -- and even when you're building completely
  34.  * platform-specific code, you can't throw across an XPCOM method boundary.)
  35.  */
  36.  
  37. const DEBUG = false; /* set to false to suppress debug messages */
  38. const PANELS_RDF_FILE  = "UPnls"; /* directory services property to find panels.rdf */
  39.  
  40. const SIDEBAR_CONTRACTID   = "@mozilla.org/sidebar;1";
  41. const SIDEBAR_CID      = Components.ID("{22117140-9c6e-11d3-aaf1-00805f8a4905}");
  42. const CONTAINER_CONTRACTID = "@mozilla.org/rdf/container;1";
  43. const DIR_SERV_CONTRACTID  = "@mozilla.org/file/directory_service;1"
  44. const NETSEARCH_CONTRACTID = "@mozilla.org/rdf/datasource;1?name=internetsearch"
  45. const nsISupports      = Components.interfaces.nsISupports;
  46. const nsIFactory       = Components.interfaces.nsIFactory;
  47. const nsISidebar       = Components.interfaces.nsISidebar;
  48. const nsIRDFContainer  = Components.interfaces.nsIRDFContainer;
  49. const nsIProperties    = Components.interfaces.nsIProperties;
  50. const nsIFileURL       = Components.interfaces.nsIFileURL;
  51. const nsIRDFRemoteDataSource = Components.interfaces.nsIRDFRemoteDataSource;
  52. const nsIInternetSearchService = Components.interfaces.nsIInternetSearchService;
  53. const nsIClassInfo = Components.interfaces.nsIClassInfo;
  54.  
  55. function nsSidebar()
  56. {
  57.     const RDF_CONTRACTID = "@mozilla.org/rdf/rdf-service;1";
  58.     const nsIRDFService = Components.interfaces.nsIRDFService;
  59.     
  60.     this.rdf = Components.classes[RDF_CONTRACTID].getService(nsIRDFService);
  61.     this.datasource_uri = getSidebarDatasourceURI(PANELS_RDF_FILE);
  62.     debug('datasource_uri is ' + this.datasource_uri);
  63.     this.resource = 'urn:sidebar:current-panel-list';
  64.     this.datasource = this.rdf.GetDataSource(this.datasource_uri);
  65. }
  66.  
  67. nsSidebar.prototype.nc = "http://home.netscape.com/NC-rdf#";
  68.  
  69. nsSidebar.prototype.setWindow =
  70. function (aWindow)
  71. {    
  72.     this.window = aWindow;    
  73. }
  74.  
  75. nsSidebar.prototype.isPanel =
  76. function (aContentURL)
  77. {
  78.     var container = 
  79.         Components.classes[CONTAINER_CONTRACTID].createInstance(nsIRDFContainer);
  80.  
  81.     container.Init(this.datasource, this.rdf.GetResource(this.resource));
  82.     
  83.     /* Create a resource for the new panel and add it to the list */
  84.     var panel_resource = 
  85.         this.rdf.GetResource("urn:sidebar:3rdparty-panel:" + aContentURL);
  86.  
  87.     return (container.IndexOf(panel_resource) != -1);
  88. }
  89.  
  90. function sidebarURLSecurityCheck(url)
  91. {
  92.     if (url.search(/(^http:|^ftp:|^https:)/) == -1)
  93.         throw "Script attempted to add sidebar panel from illegal source";
  94. }
  95.  
  96. /* decorate prototype to provide ``class'' methods and property accessors */
  97. nsSidebar.prototype.addPanel =
  98. function (aTitle, aContentURL, aCustomizeURL)
  99. {
  100.     debug("addPanel(" + aTitle + ", " + aContentURL + ", " +
  101.           aCustomizeURL + ")");
  102.  
  103.     if (!this.window)
  104.     {
  105.         debug ("no window object set, bailing out.");
  106.         throw Components.results.NS_ERROR_NOT_INITIALIZED;
  107.     }
  108.  
  109.     sidebarURLSecurityCheck(aContentURL);
  110.  
  111.     // Create a "container" wrapper around the current panels to
  112.     // manipulate the RDF:Seq more easily.
  113.     var panel_list = this.datasource.GetTarget(this.rdf.GetResource(this.resource), this.rdf.GetResource(nsSidebar.prototype.nc+"panel-list"), true);
  114.     if (panel_list) {
  115.         panel_list.QueryInterface(Components.interfaces.nsIRDFResource);
  116.     } else {
  117.         // Datasource is busted. Start over.
  118.         debug("Sidebar datasource is busted\n");
  119.   }
  120.  
  121.     var container = Components.classes[CONTAINER_CONTRACTID].createInstance(nsIRDFContainer);
  122.     container.Init(this.datasource, panel_list);
  123.  
  124.     /* Create a resource for the new panel and add it to the list */
  125.     var panel_resource = 
  126.         this.rdf.GetResource("urn:sidebar:3rdparty-panel:" + aContentURL);
  127.     var panel_index = container.IndexOf(panel_resource);
  128.     if (panel_index != -1)
  129.     {
  130.         var titleMessage, dialogMessage;
  131.         try {
  132.             var stringBundle = getStringBundle("chrome://communicator/locale/sidebar/sidebar.properties");
  133.             if (stringBundle) {
  134.                 titleMessage = stringBundle.GetStringFromName("dupePanelAlertTitle");
  135.                 dialogMessage = stringBundle.GetStringFromName("dupePanelAlertMessage");
  136.                 dialogMessage = dialogMessage.replace(/%url%/, aContentURL);
  137.             }
  138.         }
  139.         catch (e) {
  140.             titleMessage = "My Sidebar";
  141.             dialogMessage = aContentURL + " already exists in My Sidebar.";
  142.         }
  143.           
  144.         var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService();
  145.         if (promptService) {
  146.           promptService = promptService.QueryInterface(Components.interfaces.nsIPromptService);
  147.           promptService.alert(this.window, titleMessage, dialogMessage);
  148.         }
  149.  
  150.         return;
  151.     }
  152.     
  153.     var titleMessage, dialogMessage;
  154.     try {
  155.         var stringBundle = getStringBundle("chrome://communicator/locale/sidebar/sidebar.properties");
  156.         if (stringBundle) {
  157.             titleMessage = stringBundle.GetStringFromName("addPanelConfirmTitle");
  158.             dialogMessage = stringBundle.GetStringFromName("addPanelConfirmMessage");
  159.             dialogMessage = dialogMessage.replace(/%title%/, aTitle);
  160.             dialogMessage = dialogMessage.replace(/%url%/, aContentURL);
  161.             dialogMessage = dialogMessage.replace(/#/g, "\n");
  162.         }
  163.     }
  164.     catch (e) {
  165.         titleMessage = "Add Tab to My Sidebar";
  166.         dialogMessage = "Add the Tab '" + aTitle + "' to My Sidebar?\n\n" + "Source: " + aContentURL;
  167.     }
  168.           
  169.     var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService();
  170.     promptService = promptService.QueryInterface(Components.interfaces.nsIPromptService);
  171.     var rv = promptService.confirm(this.window, titleMessage, dialogMessage);
  172.       
  173.     if (!rv)
  174.         return;
  175.  
  176.     /* Now make some sidebar-ish assertions about it... */
  177.     this.datasource.Assert(panel_resource,
  178.                            this.rdf.GetResource(this.nc + "title"),
  179.                            this.rdf.GetLiteral(aTitle),
  180.                            true);
  181.     this.datasource.Assert(panel_resource,
  182.                            this.rdf.GetResource(this.nc + "content"),
  183.                            this.rdf.GetLiteral(aContentURL),
  184.                            true);
  185.     if (aCustomizeURL)
  186.         this.datasource.Assert(panel_resource,
  187.                                this.rdf.GetResource(this.nc + "customize"),
  188.                                this.rdf.GetLiteral(aCustomizeURL),
  189.                                true);
  190.         
  191.     container.AppendElement(panel_resource);
  192.  
  193.     // Use an assertion to pass a "refresh" event to all the sidebars.
  194.     // They use observers to watch for this assertion (in sidebarOverlay.js).
  195.     this.datasource.Assert(this.rdf.GetResource(this.resource),
  196.                            this.rdf.GetResource(this.nc + "refresh"),
  197.                            this.rdf.GetLiteral("true"),
  198.                            true);
  199.     this.datasource.Unassert(this.rdf.GetResource(this.resource),
  200.                              this.rdf.GetResource(this.nc + "refresh"),
  201.                              this.rdf.GetLiteral("true"));
  202.  
  203.     /* Write the modified panels out. */
  204.     this.datasource.QueryInterface(nsIRDFRemoteDataSource).Flush();
  205.  
  206. }
  207.  
  208. /* decorate prototype to provide ``class'' methods and property accessors */
  209. nsSidebar.prototype.addSearchEngine =
  210. function (engineURL, iconURL, suggestedTitle, suggestedCategory)
  211. {
  212.     debug("addSearchEngine(" + engineURL + ", " + iconURL + ", " +
  213.           suggestedCategory + ", " + suggestedTitle + ")");
  214.  
  215.     if (!this.window)
  216.     {
  217.         debug ("no window object set, bailing out.");
  218.         throw Components.results.NS_ERROR_NOT_INITIALIZED;
  219.     }
  220.  
  221.     try
  222.     {
  223.         // make sure using HTTP (for both engine as well as icon URLs)
  224.  
  225.         if (engineURL.search(/^http:\/\//i) == -1)
  226.         {
  227.             debug ("must use HTTP to fetch search engine file");
  228.             throw Components.results.NS_ERROR_INVALID_ARG;
  229.         }
  230.  
  231.         if (iconURL.search(/^http:\/\//i) == -1)
  232.         {
  233.             debug ("must use HTTP to fetch search icon file");
  234.             throw Components.results.NS_ERROR_INVALID_ARG;
  235.         }
  236.  
  237.         // make sure engineURL refers to a .src file
  238.         if (engineURL.search(/\.src$/i) == -1)
  239.         {
  240.             debug ("engineURL doesn't reference a .src file");
  241.             throw Components.results.NS_ERROR_INVALID_ARG;
  242.         }
  243.  
  244.         // make sure iconURL refers to a .gif/.jpg/.jpeg/.png file
  245.         if (iconURL.search(/\.(gif|jpg|jpeg|png)$/i) == -1)
  246.         {
  247.             debug ("iconURL doesn't reference a supported image file");
  248.             throw Components.results.NS_ERROR_INVALID_ARG;
  249.         }
  250.  
  251.     }
  252.     catch(ex)
  253.     {
  254.         this.window.alert("Failed to add the search engine.\n");
  255.         throw Components.results.NS_ERROR_INVALID_ARG;
  256.     }
  257.  
  258.     var titleMessage, dialogMessage;
  259.     try {
  260.         var stringBundle = getStringBundle("chrome://communicator/locale/sidebar/sidebar.properties");
  261.         if (stringBundle) {
  262.             titleMessage = stringBundle.GetStringFromName("addEngineConfirmTitle");
  263.             dialogMessage = stringBundle.GetStringFromName("addEngineConfirmMessage");
  264.             dialogMessage = dialogMessage.replace(/%title%/, suggestedTitle);
  265.             dialogMessage = dialogMessage.replace(/%category%/, suggestedCategory);
  266.             dialogMessage = dialogMessage.replace(/%url%/, engineURL);
  267.             dialogMessage = dialogMessage.replace(/#/g, "\n");
  268.         }
  269.     }
  270.     catch (e) {
  271.         titleMessage = "Add Search Engine";
  272.         dialogMessage = "Add the following search engine?\n\nName: " + suggestedTitle;
  273.         dialogMessage += "\nSearch Category: " + suggestedCategory;
  274.         dialogMessage += "\nSource: " + engineURL;
  275.     }
  276.           
  277.     var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService();
  278.     promptService = promptService.QueryInterface(Components.interfaces.nsIPromptService);
  279.     var rv = promptService.confirm(this.window, titleMessage, dialogMessage);
  280.       
  281.     if (!rv)
  282.         return;
  283.  
  284.     var internetSearch = Components.classes[NETSEARCH_CONTRACTID].getService();
  285.     if (internetSearch)    
  286.         internetSearch = internetSearch.QueryInterface(nsIInternetSearchService);
  287.     if (internetSearch)
  288.     {
  289.         internetSearch.AddSearchEngine(engineURL, iconURL, suggestedTitle,
  290.                                        suggestedCategory);
  291.     }
  292. }
  293.  
  294. // property of nsIClassInfo
  295. nsSidebar.prototype.flags = nsIClassInfo.DOM_OBJECT;
  296.  
  297. // property of nsIClassInfo
  298. nsSidebar.prototype.classDescription = "Sidebar";
  299.  
  300. nsSidebar.prototype.QueryInterface =
  301. function (iid) {
  302.     if (!iid.equals(nsISidebar) && 
  303.         !iid.equals(nsIClassInfo) &&
  304.         !iid.equals(nsISupports))
  305.         throw Components.results.NS_ERROR_NO_INTERFACE;
  306.     return this;
  307. }
  308.  
  309. var sidebarModule = new Object();
  310.  
  311. sidebarModule.registerSelf =
  312. function (compMgr, fileSpec, location, type)
  313. {
  314.     debug("registering (all right -- a JavaScript module!)");
  315.     compMgr.registerComponentWithType(SIDEBAR_CID, "Sidebar JS Component",
  316.                                       SIDEBAR_CONTRACTID, fileSpec, location,
  317.                                       true, true, type);
  318. }
  319.  
  320. sidebarModule.getClassObject =
  321. function (compMgr, cid, iid) {
  322.     if (!cid.equals(SIDEBAR_CID))
  323.         throw Components.results.NS_ERROR_NO_INTERFACE;
  324.     
  325.     if (!iid.equals(Components.interfaces.nsIFactory))
  326.         throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  327.     
  328.     return sidebarFactory;
  329. }
  330.  
  331. sidebarModule.canUnload =
  332. function(compMgr)
  333. {
  334.     debug("Unloading component.");
  335.     return true;
  336. }
  337.     
  338. /* factory object */
  339. sidebarFactory = new Object();
  340.  
  341. sidebarFactory.createInstance =
  342. function (outer, iid) {
  343.     debug("CI: " + iid);
  344.     if (outer != null)
  345.         throw Components.results.NS_ERROR_NO_AGGREGATION;
  346.  
  347.     return (new nsSidebar()).QueryInterface(iid);
  348. }
  349.  
  350. /* entrypoint */
  351. function NSGetModule(compMgr, fileSpec) {
  352.     return sidebarModule;
  353. }
  354.  
  355. /* static functions */
  356. if (DEBUG)
  357.     debug = function (s) { dump("-*- sidebar component: " + s + "\n"); }
  358. else
  359.     debug = function (s) {}
  360.  
  361. function getSidebarDatasourceURI(panels_file_id)
  362. {
  363.     try 
  364.     {
  365.         /* use the fileLocator to look in the profile directory 
  366.          * to find 'panels.rdf', which is the
  367.          * database of the user's currently selected panels. */
  368.         var directory_service = Components.classes[DIR_SERV_CONTRACTID].getService();
  369.         if (directory_service)
  370.             directory_service = directory_service.QueryInterface(Components.interfaces.nsIProperties);
  371.  
  372.         /* if <profile>/panels.rdf doesn't exist, get will copy
  373.          *bin/defaults/profile/panels.rdf to <profile>/panels.rdf */
  374.         var sidebar_file = directory_service.get(panels_file_id, Components.interfaces.nsIFile);
  375.  
  376.         if (!sidebar_file.exists())
  377.         {
  378.             /* this should not happen, as GetFileLocation() should copy
  379.              * defaults/panels.rdf to the users profile directory */
  380.             debug("sidebar file does not exist");
  381.             return null;
  382.         }
  383.  
  384.         debug("sidebar uri is " + sidebar_file.URL);
  385.         return sidebar_file.URL;
  386.     }
  387.     catch (ex)
  388.     {
  389.         /* this should not happen */
  390.         debug("caught " + ex + " getting sidebar datasource uri");
  391.         return null;
  392.     }
  393. }
  394.  
  395. function getStringBundle(aURL) 
  396. {
  397.   var stringBundleService = Components.classes["@mozilla.org/intl/stringbundle;1"].getService();
  398.   stringBundleService = stringBundleService.QueryInterface(Components.interfaces.nsIStringBundleService);
  399.   var appLocale;
  400.   var localeService = Components.classes["@mozilla.org/intl/nslocaleservice;1"].getService();
  401.   if (localeService)
  402.     localeService = localeService.QueryInterface(Components.interfaces.nsILocaleService);
  403.   if (localeService)
  404.     appLocale = localeService.GetApplicationLocale();
  405.   var stringBundle = stringBundleService.CreateBundle(aURL, appLocale);
  406.   if (stringBundle)
  407.     return stringBundle.QueryInterface(Components.interfaces.nsIStringBundle);
  408. }
  409.